﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

using GalaSoft.MvvmLight.Command;

using Holdem.Core.Entities.StartingHands;
using Holdem.Core.Statistics;
using Holdem.Interfaces;
using Holdem.Interfaces.Card;
using Holdem.Interfaces.Configuration;
using Holdem.Interfaces.Database;
using Holdem.Interfaces.ReplayEngine;
using Holdem.Interfaces.Service;
using Holdem.Interfaces.ViewModel;

using Microsoft.Phone.Reactive;

namespace Holdem.ViewModel
{
    public class HoldemOptionsViewModel : HoldemViewModelBase, IHoldemOptionsViewModel
    {
        #region Instance Variables

        private static readonly ObservableCollection<string> _searchFilters =
            new ObservableCollection<string>
			{
				".xml",
				".txt",
				"*.*"
			};

		private readonly IReplayEngineHost _engineHost;
        private readonly IHandHistoryDataContext _dataContext;

        private IntRangeDataSource _precisionData;

        #endregion

        #region Public Properties

        public RelayCommand DeleteHandHsitoryCommand
        {
            get;
            private set;
        }

		public IEnumerable<string> AvailableEngines { get { return _engineHost.EngineNames; } }

        public ObservableCollection<string> SearchFilter
        {
            get
            {
                return _searchFilters;
            }
        }

        public int SkipScaleChange
        {
            get
            {
                return PersistConfig.Get<int>(ConfigKey.HoldemOptionsViewSkipScale);
            }
            set
            {
                PersistConfig[ConfigKey.HoldemOptionsViewSkipScale] = value;
                base.RaisePropertyChanged("SkipScaleChange");
            }
        }

        public string UserName
        {
            get
            {
                return PersistConfig.Get<string>(ConfigKey.HoldemOptionsViewUserName);
            }
            set
            {
                PersistConfig[ConfigKey.HoldemOptionsViewUserName] = value;
                base.RaisePropertyChanged("UserName");
            }
        }

        public string SelectedReplayEngine
        {
            get
            {
                return PersistConfig.Get<string>(ConfigKey.HoldemOptionsViewSelectedReplayEngine);
            }
            set
            {
                PersistConfig[ConfigKey.HoldemOptionsViewSelectedReplayEngine] = value;
                base.RaisePropertyChanged("SelectedReplayEngine");
            }
        }

        public string SelectedSearchFilter
        {
            get
            {
                return PersistConfig.Get<string>(ConfigKey.HoldemOptionsViewSelectedSearchFilter);
            }
            set
            {
                PersistConfig[ConfigKey.HoldemOptionsViewSelectedSearchFilter] = value;
                base.RaisePropertyChanged("SelectedSearchFilter");
            }
        }

        public bool ResursiveSearch
        {
            get
            {
                return PersistConfig.Get<bool>(ConfigKey.HoldemOptionsViewRecursiveSearch);
            }
            set
            {
                PersistConfig[ConfigKey.HoldemOptionsViewRecursiveSearch] = value;
                base.RaisePropertyChanged("ResursiveSearch");
            }
        }

        public bool HandPreview
        {
            get
            {
                return PersistConfig.Get<bool>(ConfigKey.HoldemOptionsViewPreview);
            }
            set
            {
                PersistConfig[ConfigKey.HoldemOptionsViewPreview] = value;
                base.RaisePropertyChanged("HandPreview");
            }
        }

        public bool WriteHandHistory
        {
            get
            {
                return PersistConfig.Get<bool>(ConfigKey.HoldemOptionsViewWriteHandHistory);
            }
            set
            {
                PersistConfig[ConfigKey.HoldemOptionsViewWriteHandHistory] = value;
                base.RaisePropertyChanged("WriteHandHistory");
            }
        }

        public bool CardAnimations
        {
            get
            {
                return PersistConfig.Get<bool>(ConfigKey.HoldemOptoinsViewCardAnimations);
            }
            set
            {
                PersistConfig[ConfigKey.HoldemOptoinsViewCardAnimations] = value;
                base.RaisePropertyChanged("CardAnimations");
            }
        }

        public bool IsHandHistorySaved
        {
            get { return !_dataContext.IsEmpty(); }
        }

        public IntRangeDataSource PrecisionData
        {
            get
            {
                return _precisionData;
            }
        }

        #endregion

        #region Constructor

        public HoldemOptionsViewModel(
            IHandHistoryDataContext dataContext,
			IReplayEngineHost engineHost,
			ICardThemeManager themeManager,
			IConfigurationService configService,
            IAdProvider adProvider)
			: base(themeManager, configService, adProvider)
        {
			if (engineHost == null)
				throw new ArgumentNullException("engineHost");
            if( dataContext == null )
                throw new ArgumentNullException("dataContext");

            _dataContext = dataContext;
            _dataContext.HandHistoryDeletedAllEvent += this.HandHistoryDeleted;

			_engineHost = engineHost;

            DeleteHandHsitoryCommand = 
                new RelayCommand(
                    () =>
                    {
                        base.VisibilityChanged("Visibility3");

                        Scheduler.Dispatcher.Schedule(
                            () => _dataContext.DeleteHandHistory());
                    });

            LoadSavedConfiguration();
        }

        #endregion

        #region Private Methods

        private void HandHistoryDeleted(object sender, HandHistoryDeletedAllEventArgs e)
        {
            Scheduler.Dispatcher.Schedule(
                () =>
                {
                    RaisePropertyChanged("IsHandHistorySaved");
                    base.VisibilityChanged("Visibility3");
                });
        }

        private void LoadSavedConfiguration()
        {
            this.SelectedReplayEngine = PersistConfig.Get<string>(ConfigKey.HoldemOptionsViewSelectedReplayEngine); 
            this.SkipScaleChange = PersistConfig.Get<int>(ConfigKey.HoldemOptionsViewSkipScale);
            base.NumberOfPlayers = PersistConfig.Cast<int>(ConfigKey.HoldemOptionsViewNumberOfPlayers);
            this.UserName = PersistConfig.Get<string>(ConfigKey.HoldemOptionsViewUserName);
            this.WriteHandHistory = PersistConfig.Get<bool>(ConfigKey.HoldemOptionsViewWriteHandHistory);
            this.CardAnimations = PersistConfig.Get<bool>(ConfigKey.HoldemOptoinsViewCardAnimations);

            this.PlayersData.SelectedItem = base.NumberOfPlayers;

            _precisionData = new IntRangeDataSource(1, (int)HoldemStatisticsBase.MaxPrecision);

            base.PlayersData.SelectionChanged 
                += (o, e) =>
                {
                    base.NumberOfPlayers = (int)e.AddedItems[0];
                };
            _precisionData.SelectionChanged
                += (o, e) =>
                {
                    this.Precision = (int)e.AddedItems[0];
                };
        }

        #endregion
    }
}